/*
* BSTimeline
*
* Ken Frederick
* frederickk@google.com
*
*/


var BSTimeline = function(container, parameters) {
    // ------------------------------------------------------------------------
    //
    // Properties
    //
    // ------------------------------------------------------------------------
    // instantiate a base to share common
    // properties and methods across BSTimeline classes
    // (bootleg inheritance :)
    var base = BSTimelineBase;

    container = container || document.body;

    var properties = base.combine({
        months    : '',
        year      : 2015,
        dateRange : [],
        color     : 'rgba(30, 20, 15, 0.9)',
        tickWidth : '1px'
    }, parameters);

    var width = container.offsetWidth;
    var height = container.offsetHeight;

    // TODO: don't make this static, let user define this
    var y = [160, 24];

    var totalMonths;
    var totalDays;
    var ticks;
    var spacing;



    // ------------------------------------------------------------------------
    //
    // Methods
    //
    // ------------------------------------------------------------------------
    (function init() {
        if (properties.dateRange.length === 2) {
            properties.months = getRange(properties.dateRange[0], properties.dateRange[1]);
        }
        else if (properties.dateRange.length === 0 && properties.months === '') {
            alert('BSTimeline Error: Missing date range');
        }

        totalMonths = properties.months.length;
        totalDays = calculateDays();
        ticks = [];
        spacing = ((width/totalDays) < 9)
            ? 9
            : (width/totalDays);
    })();


    // ------------------------------------------------------------------------
    /**
     * Create an element with a tick mark and a day label (if spacing allows)
     *
     * @param  {number} index  day in month
     *
     * @return {HTMLNode} the corresponding HTML node of the element
     *
     */
    var dayElement = function(index) {
        var e = document.createElement('div');
        e.style.position = 'absolute';
        var c = new CSSTwo(e);

        // tickmark
        tick = c.line(
            index * spacing, // x
            (index == 0) ? y[0] - 50 : y[0], // y
            index * spacing,
            y[0] + y[1],
            {
                id          : 'tick-' + index,
                borderColor : properties.color,
                borderWidth : properties.tickWidth
            }
        );

        // day label
        if (spacing > 20) {
            day = c.text(
                8 + (index * spacing), // x
                y[0] + y[1] - 10,      // y
                index + 1,
                {
                    id    : 'day-' + index,
                    color : properties.color
                }
            );
        }
        ticks.push(index * spacing);

        // day box


        return e;
    };

    /**
     * Create a month label (if spacing allows)
     *
     * @param  {string} name  name of the month
     *
     * @return {HTMLNode} the corresponding HTML node of the element
     *
     */
    var monthElement = function(name) {
        var e = document.createElement('div');
        e.style.position = 'absolute';
        var c = new CSSTwo(e);

        var index = base.months_MMMM.indexOf(name);
        var date = new Date(properties.year, index + 1, 0);

        var d;
        var m;
        for (var i = 0; i < date.getDate(); i++) {
            console.log(date);

            // month label
            if (i == 0) {
                m = c.text(
                    8 + (i * spacing), // x
                    y[0] + y[1] - 50,  // y
                    name,
                    {
                        id    : 'month-' + name,
                        color : properties.color
                    }
                );
                e.appendChild(m);
            }

            // day
            d = dayElement(i);
            e.appendChild(d);
        }
        e.style.width = (i * spacing) + 'px';

        container.appendChild(e);

        return e;
    };


    // ------------------------------------------------------------------------
    /**
     * Render the entire timeline to the screen
     *
     */
    function draw() {
        var x = 0;

        // months/days
        for (var i = 0; i < totalMonths; i++) {
            var m = monthElement(properties.months[i]);
            m.style.left = x + 'px';
            x += parseInt(m.style.width, 10);
        }
    };



    // ------------------------------------------------------------------------
    //
    // Gets
    //
    // ------------------------------------------------------------------------
    /**
     * Determine the range of the entire timeline
     *
     * @param  {string} start start date
     * @param  {string} end   end date
     *
     * @return {array} the date range as an array
     *
     */
    function getRange(start, end) {
        var range = [];
        var s = new Date(start).getMonth();
        var e = new Date(end).getMonth();
        e = (e < s)
            ? e += 12
            : e;

        for (var m = s; m <= e; m++) {
            range.push(base.months_MMMM[m % 12]);
        }

        return range;
    };

    // ------------------------------------------------------------------------
    /**
     * Calculate the total number of days
     *
     * @return {number} the total number of days calculated
     *
     */
    function calculateDays() {
        var total = 0;
        for (var i = 0; i < totalMonths; i++) {
            var index = base.months_MMMM.indexOf(name);
            // TODO: insist properties.year comes from a valid date object
            var d = new Date(properties.year, index + 1, 0);
            total += d.getDate();
        }

        return total;
    };



    // ------------------------------------------------------------------------
    return {
        ticks   : ticks,
        spacing : spacing,
        height  : (y[0] + y[1]),
        draw    : draw
    };

};


